<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0,maximum-scale=1.0, user-scalable=no"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
    <meta name="renderer" content="webkit">
    <meta http-equiv="Cache-Control" content="no-siteapp"/>
    <link rel="stylesheet" href="common/css/mdui.min.css"/>
    <link rel="stylesheet" href="common/css/paging.css"/>
    <script src="/api.js"></script>
    <script src="common/js/jquery.min.js"></script>
    <script src="common/js/paging.js"></script>
    <script src="common/js/mdui.min.js"></script>
    <title>内网穿透</title>
</head>
<body class="mdui-drawer-body-left mdui-appbar-with-toolbar  mdui-theme-primary-indigo mdui-theme-accent-pink mdui-theme-layout-auto">
<header class="mdui-appbar mdui-appbar-fixed">
    <div class="mdui-toolbar mdui-color-theme">
        <span class="mdui-btn mdui-btn-icon mdui-ripple mdui-ripple-white"
              mdui-drawer="{target: '#main-drawer', swipe: true}"><i class="mdui-icon material-icons">menu</i></span>
        <a href="center.html" class="mdui-typo-headline mdui-hidden-xs">内网穿透</a>
        <div class="mdui-toolbar-spacer"></div>
        <div class=" mdui-btn mdui-btn-dense"><span>用户：<span id="username">***</span> 级别：<span
                id="level">***</span> </span></div>
        <div id="login_out" class=" mdui-btn mdui-btn-dense">退出</div>
    </div>
</header>
<div class="mdui-drawer" id="main-drawer">
    <div class="mdui-list" mdui-collapse="{accordion: true}" style="margin-bottom: 76px;">
        <div class="mdui-collapse-item mdui-collapse-item-open">
            <a class="mdui-collapse-item-header mdui-list-item mdui-ripple" href="center.html">
                <i class="mdui-list-item-icon mdui-icon material-icons mdui-text-color-blue">near_me</i>
                <div class="mdui-list-item-content">穿透服务</div>
            </a>
            <a class="mdui-collapse-item mdui-collapse-item-open" href="./port.html">
                <div class="mdui-collapse-item-header mdui-list-item mdui-ripple">
                    <i class="mdui-list-item-icon mdui-icon  material-icons mdui-text-color-purple">layers</i>
                    <div class="mdui-list-item-content">端口管理</div>
                </div>
            </a>
            <a class="mdui-collapse-item mdui-collapse-item-open" href="domain.html">
                <div class="mdui-collapse-item-header mdui-list-item mdui-ripple">
                    <i class="mdui-list-item-icon mdui-icon material-icons mdui-text-color-green">layers</i>
                    <div class="mdui-list-item-content">域名管理</div>
                </div>
            </a>
            <a class="mdui-collapse-item mdui-collapse-item-open" href="autoproxy.html">
                <div class="mdui-collapse-item-header mdui-list-item mdui-ripple">
                    <i class="mdui-list-item-icon mdui-icon  material-icons mdui-text-color-cyan-300">layers</i>
                    <div class="mdui-list-item-content">自动穿透</div>
                </div>
            </a>
            <a class="mdui-collapse-item mdui-collapse-item-open" href="log.html">
                <div class="mdui-collapse-item-header mdui-list-item mdui-ripple">
                    <i class="mdui-list-item-icon mdui-icon material-icons mdui-text-color-blue">layers</i>
                    <div class="mdui-list-item-content">穿透日志</div>
                </div>
            </a>
        </div>
    </div>
</div>

<script>
    $(function () {
        var userInfo = localStorage.getItem("userInfo")
        if (!userInfo) {
            location.href = "login.html";
        } else {
            userInfo = JSON.parse(userInfo)
            $("#username").text(userInfo.username)
            $("#level").text(userInfo.level)
        }
        $("#login_out").click(function () {
            localStorage.removeItem("userInfo")
            location.href = "login.html"
        })
    })
</script>

<div style="padding: 1rem">

    <div style="padding: .6rem;display: flex;align-items: center;justify-content: space-between;">
        <button class="mdui-btn mdui-btn-raised mdui-btn-dense mdui-color-deep-purple-accent mdui-ripple"
                onclick="new mdui.Dialog('#addUser').open()">
            添加穿透配置
        </button>
        <div>设备ID:<span id="deviceIdText">未设置设备ID</span></div>
    </div>

    <div class="mdui-table-fluid">
        <table class="mdui-table">
            <thead>
            <tr>
                <th>设备ID</th>
                <th>内网服务</th>
                <th>外网服务</th>
                <th>穿透类型</th>
                <th>穿透域名</th>
                <th>穿透端口</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody id="tabData">

            </tbody>
        </table>
    </div>

    <div style="padding: .6rem;word-break: break-all;line-height: 1.6 ">
        <p>当前设备ID:
        <p id="deviceId">如果未设置设备ID(意味着你用不了这个功能)</p></p>
        <p style="letter-spacing:.1rem">
            <br>功能说明：<br>如果你在这里添加了云端存储，那么HP启动时就会加载云端配置，然后进行内网穿透，减少了每次打开都需要重新填写配置这种反人类的，头大的事情。该功能要求设备ID。
            <br> <br>如何设置:<br>
        <ul>
            <li>设备ID要求：自定义10-36个字符串长度可以是字母或者数字（不要和别人冲突了，不要泄露了）</li>
            <li>android中：自动获取IMIE为设备ID</li>
            <li>docker中：添加环境变量 deviceId:设备ID</li>
            <li>二进制文件：hp-client -deviceId=设备ID</li>
        </ul>
        </p>
    </div>

    <div class="mdui-dialog" id="addUser" style="overflow: scroll">
        <form id="handle-form">
            <div class="mdui-dialog-content">
                <div class="mdui-textfield">
                    <label class="mdui-textfield-label">内网服务</label>
                    <input class="mdui-textfield-input" name="userHost" placeholder="内网服务（ip:端口）" type="text"/>
                </div>

                <div class="mdui-textfield" id="type">
                    <label class="mdui-textfield-label">穿透类型</label>
                    <label class="mdui-radio" style="margin-right: 20px">
                        <input type="radio" value="TCP" name="type" checked/>
                        <i class="mdui-radio-icon"></i>
                        TCP
                    </label>
                    <label class="mdui-radio" style="margin-right: 20px">
                        <input type="radio" value="UDP" name="type"/>
                        <i class="mdui-radio-icon"></i>
                        UDP
                    </label>
                    <label class="mdui-radio" style="margin-right: 20px">
                        <input type="radio" value="TCP_UDP" name="type"/>
                        <i class="mdui-radio-icon"></i>
                        TCP+UDP
                    </label>
                </div>

                <div class="mdui-textfield" id="server_data">
                    <label class="mdui-textfield-label">穿透服务选择</label>
                </div>

                <div style="display: none;" class="mdui-textfield" id="showServerInfoInPut">
                    <label class="mdui-textfield-label">自定义穿透服务</label>
                    <input class="mdui-textfield-input" id="showServerInfoInPutVal" placeholder="ip:端口" type="text"/>
                </div>

                <div class="mdui-textfield" id="domains">
                </div>
                <div class="mdui-textfield" id="ports">
                </div>
            </div>
            <div class="mdui-dialog-actions">
                <div id="closeFrom" class="mdui-btn mdui-ripple" mdui-dialog-cancel>取消</div>
                <div id="add_btn" class="mdui-btn mdui-ripple">确定</div>
            </div>
        </form>
    </div>
</div>


<script>
    var userInfo = localStorage.getItem("userInfo")
    var deviceId = "NO_ID"
    if (userInfo) {
        userInfo = JSON.parse(userInfo)
        console.log(userInfo)

        //获取设备ID：
        $.get("/device/info", function (result) {
            if (result !== "NO_ID") {
                deviceId = result
                $("#deviceIdText").text(result.slice(0, 6) + "..." + result.slice(-6))
                $("#deviceId").text(deviceId)
            }
        });

        /**
         * 初始化参数
         */
        function initPop() {
            var domainHtml = "      <label class=\"mdui-textfield-label\">穿透域名</label>\n" +
                "                    "

            for (let a of Object.keys(userInfo.domains)) {
                domainHtml += "<label style='margin-right: 20px' class=\"mdui-radio\">\n" +
                    "                        <input type=\"radio\" value='" + a + "' name=\"domain\"/>\n" +
                    "                        <i class=\"mdui-radio-icon\"></i>\n" +
                    "                        " + a + "\n" +
                    "                    </label>"
            }
            $("#domains").html(
                domainHtml
            )

            var portsHtml = "<label style='margin-right: 20px' class=\"mdui-textfield-label\">外网端口号</label>     <label class=\"mdui-radio\">\n" +
                "                        <input type=\"radio\" value='0' name=\"port\"/>\n" +
                "                        <i class=\"mdui-radio-icon\"></i>\n" +
                "                        随机端口\n" +
                "                    </label>"
            for (let a of userInfo.ports) {
                portsHtml += "<label style='margin-right: 20px' class=\"mdui-radio\">\n" +
                    "                        <input type=\"radio\" value='" + a + "' name=\"port\"/>\n" +
                    "                        <i class=\"mdui-radio-icon\"></i>\n" +
                    "                        " + a + "\n" +
                    "                    </label>"
            }
            $("#ports").html(
                portsHtml
            )

            var serverData = []

            $.get(apiAddress + "/load/data", function (result) {
                if (result.code === 200) {
                    serverData.push(...result.data)
                }

                var serverDataHtml = "             <label class=\"mdui-textfield-label\">穿透服务选择</label>\n"

                for (let a of serverData) {
                    serverDataHtml += "<label style='margin-right: 20px' class=\"mdui-radio\">\n" +
                        "                        <input type=\"radio\" value='" + a.ip + ":" + a.port + "' name=\"serverHost\"/>\n" +
                        "                        <i class=\"mdui-radio-icon\"></i>\n" +
                        "                        " + a.name + "在线数：" + a.num + "\n" +
                        "                    </label>"
                }
                serverDataHtml += "<label style='margin-right: 20px' class=\"mdui-radio\">\n" +
                    "                        <input type=\"radio\" value='-1' name=\"serverHost\"/>\n" +
                    "                        <i class=\"mdui-radio-icon\"></i>\n" +
                    "                        " + "自定义服务" + "\n" +
                    "                    </label>"

                $("#server_data").html(
                    serverDataHtml
                )

                $("#server_data :radio").on("click", function () {
                    if ($(this).val() == -1) {
                        $("#showServerInfoInPut").show()
                    } else {
                        $("#showServerInfoInPut").hide()
                    }
                })

                $("#type :radio").on("click", function () {
                    if ($(this).val() == 'UDP') {
                        $("#domains").hide()
                    } else {
                        $("#domains").show()
                    }
                })

            });
        }

        initPop();

        function stop(id) {
            $.get(apiAddress + "/config/remove?id=" + id, function (result) {
                alert(result.msg)
                reload()
            });
        }

        $("#userInfo").val(userInfo.id)
        var tabData = ""
        $.get(apiAddress + "/config/list?userId=" + userInfo.id, function (result) {
            for (let a of result.data) {
                let port = a.port;
                tabData += "  <tr>\n" +
                    "                <td>" + (a.deviceId.slice(0, 6) + "..." + a.deviceId.slice(-6)) + "</td>\n" +
                    "                <td>" + a.userHost + "</td>\n" +
                    "                <td>" + a.serverHost + "</td>\n" +
                    "                <td>" + a.type + "</td>\n" +
                    "                <td>" + a.domain + "</td>\n" +
                    "                <td>" + a.port + "</td>\n" +
                    "                <td>\n" +
                    "                    <button class=\"mdui-btn mdui-btn-raised mdui-btn-dense mdui-color-deep-orange-accent mdui-ripple\"\n" +
                    "                       onclick=\"stop('" + a.id + "')\">\n" +
                    "                        删除\n" +
                    "                    </button>\n" +
                    "                </td>\n" +
                    "            </tr>"
            }
            $("#tabData").html(
                tabData
            )
        });
    }


    $("#add_btn").click(function () {

        if (deviceId === "NO_ID") {
            alert("不能获取到设备唯一ID，因此不能使用该功能")
            return;
        }

        let serialize = $("#handle-form").serializeArray();
        //处理自定义穿透服务选项
        for (let a of serialize) {
            if (a.name == 'serverHost' && a.value == '-1') {
                a.value = $("#showServerInfoInPutVal").val()
            }
            if (a.name == 'userHost') {
                var split = a.value.split(":");
                if (split.length == 1) {
                    alert("必须填写端口，ip:端口")
                    return
                }
            }
            if (a.name == 'domian') {
                var split = a.value.split(":");
                if (split.length == 1) {
                    alert("必须填写端口，ip:端口")
                    return
                }
            }


        }
        //添加其他的post数据
        //用户ID，用户名，密码，设备ID，
        serialize.push({name: "userId", value: userInfo.id})
        serialize.push({name: "username", value: userInfo.username})
        serialize.push({name: "password", value: userInfo.password})
        serialize.push({name: "deviceId", value: deviceId})

        console.log(serialize)
        $.post(apiAddress + "/config/save", serialize, function (result) {
            if (result.code === 200) {
                alert(result.msg)
                $("#closeFrom").click();
                reload()
            } else {
                alert(result.msg)
            }
        });
    })


    /**
     * 刷新
     */
    function reload() {
        $.post(apiAddress + "/user/login", {
            username: userInfo.username,
            password: userInfo.password
        }, function (result) {
            if (result.code === 200) {
                localStorage.setItem("userInfo", JSON.stringify(result.data))
                location.reload()
            } else {
                $("#closeLogin").click()
                mdui.alert(result.msg);
            }
        });
    }

</script>

</body>
</html>
